import React, { useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Button,
  Row,
  Col,
  message,
  Modal,
  Form,
  Checkbox,
  Input,
  InputNumber,
  Space,
} from 'antd';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { connect, useIntl } from 'umi';
import Resource from './resource';
import request from '@/utils/request';
import { WhseSelect, DeptSelect } from '@/components/FormItemSelect';
import ResGrpSelect from '@/components/ResGrpSelect';
import QuickMenu from '@/components/QuickMenu';

const apiURL = '/api/services/app/ResourceGroup/';
const { confirm } = Modal;

const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [record, setRecord] = useState({ id: 0 });
  const [dataSource, setDataSource] = useState([]);
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = () => {
    request(apiURL + 'GetList', {
      method: 'GET',
    }).then((response: any) => {
      if (response && response.success) {
        setDataSource(response.result.items);
      }
    });
  };

  const onFinish = (values: any) => {
    var model = values.ResourceGroup;
    setLoading(true);
    var act = 'Modify';
    if (model.id == 0 || !model.id) {
      act = 'New';
    }
    model.calendarID = '0';
    model.opCode = '0';
    model.opStdID = '0';
    model.backflushEmpID = '0';
    model.resourceType = '0';

    request(apiURL + act, {
      method: 'POST',
      data: model,
    }).then((response) => {
      if (response) {
        if (response.success) {
          if (response.result.success) {
            message.success(intl.formatMessage({ id: 'pages.save.success' }));
            setRecord(response.result.data);
          } else {
            message.error(response.result.message);
          }
        } else {
          message.error(response.error.message);
        }
        setLoading(false);
      }
    });
  };

  const getData = (e: any) => {
    if (e.resourceGrpID) {
      request(apiURL + 'GetByCode', {
        method: 'GET',
        params: { code: e.resourceGrpID },
      }).then((response: any) => {
        if (response.success) {
          if (response.result.success) {
            formRef.current.setFieldsValue({ ResourceGroup: response.result.data });
            setRecord(response.result.data);
          } else {
            message.warning(response.result.message);
          }
        }
      });
    }
  };

  const resetForm = () => {
    formRef.current.resetFields();
    setRecord({ id: 0 });
  };

  const switchModal = () => {
    setVisible(!visible);
  };

  const delObj = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.deleteConfirm' }),
      onOk() {
        request(apiURL + 'Delete', {
          method: 'DELETE',
          data: { id: record.id },
        }).then((response) => {
          if (response) {
            resetForm();
          }
        });
      },
    });
  };

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Form {...layout} ref={formRef} onFinish={onFinish}>
            <Card
              title={intl.formatMessage({ id: 'pages.resourceGroup' })}
              extra={[
                <Space key="S1">
                  <Button type="primary" icon={<PlusOutlined />} onClick={resetForm}>
                    {intl.formatMessage({ id: 'pages.new' })}
                  </Button>
                  <Button type="primary" htmlType="submit" loading={loading}>
                    {intl.formatMessage({ id: 'pages.save' })}
                  </Button>
                  <Button danger onClick={delObj} disabled={record.id === 0}>
                    {intl.formatMessage({ id: 'pages.delete' })}
                  </Button>
                  <QuickMenu
                    path="/manufacture/resourceGroup"
                    icon="icon-document"
                    title="pages.ResourceGroup"
                  />
                </Space>,
              ]}
            >
              <Row gutter={[16, 16]}>
                <Col span={12}>
                  <Form.Item label="ID" name={['ResourceGroup', 'id']} hidden>
                    <Input />
                  </Form.Item>
                  <Form.Item label={intl.formatMessage({ id: 'pages.resourceGroup' })}>
                    <Input.Group compact>
                      <ResGrpSelect
                        width={200}
                        noStyle
                        name={['ResourceGroup', 'resourceGrpID']}
                        rules={[{ required: true, message: intl.formatMessage({ id: 'pages.resourceGroup.required' }) }]}
                        setCurrent={getData}
                      />
                    </Input.Group>
                  </Form.Item>
                  <Form.Item
                    label={intl.formatMessage({ id: 'pages.description' })}
                    name={['ResourceGroup', 'description']}
                    rules={[{ required: true }]}
                  >
                    <Input />
                  </Form.Item>
                  <DeptSelect
                    width={200}
                    showSearch
                    name={['ResourceGroup', 'jcDept']}
                    placeholder={intl.formatMessage({ id: 'pages.selectDepartment' })}
                    label={intl.formatMessage({ id: 'pages.department' })}
                  />
                  <Form.Item label={intl.formatMessage({ id: 'pages.inputWhse' })} style={{ marginBottom: 0 }}>
                    <Input.Group compact>
                      <WhseSelect
                        width={200}
                        name={['ResourceGroup', 'inputWhse']}
                        placeholder={intl.formatMessage({ id: 'pages.warehouse' })}
                      />
                      <Form.Item name={['ResourceGroup', 'inputBinNum']}>
                        <Input style={{ width: 100 }} placeholder={intl.formatMessage({ id: 'pages.binLocation' })} />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                  <Form.Item label={intl.formatMessage({ id: 'pages.outputWhse' })} style={{ marginBottom: 0 }}>
                    <Input.Group compact>
                      <WhseSelect
                        width={200}
                        name={['ResourceGroup', 'outputWhse']}
                        placeholder={intl.formatMessage({ id: 'pages.warehouse' })}
                      />
                      <Form.Item name={['ResourceGroup', 'outputBinNum']}>
                        <Input style={{ width: 100 }} placeholder={intl.formatMessage({ id: 'pages.binLocation' })} />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                  <Form.Item label={intl.formatMessage({ id: 'pages.backflushWhse' })} style={{ marginBottom: 0 }}>
                    <Input.Group compact>
                      <WhseSelect
                        width={200}
                        name={['ResourceGroup', 'backflushWhse']}
                        placeholder={intl.formatMessage({ id: 'pages.warehouse' })}
                      />
                      <Form.Item name={['ResourceGroup', 'backflushBinNum']}>
                        <Input style={{ width: 100 }} placeholder={intl.formatMessage({ id: 'pages.binLocation' })} />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item style={{ marginBottom: 0 }} wrapperCol={{ offset: 5 }}>
                    <Input.Group compact>
                      <Form.Item name={['ResourceGroup', 'inActive']} valuePropName="checked">
                        <Checkbox>{intl.formatMessage({ id: 'pages.inactive' })}</Checkbox>
                      </Form.Item>
                      <Form.Item name={['ResourceGroup', 'subContract']} valuePropName="checked">
                        <Checkbox>{intl.formatMessage({ id: 'pages.subContract' })}</Checkbox>
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>

                  <Form.Item label={intl.formatMessage({ id: 'pages.queueTime' })} name={['ResourceGroup', 'queHours']}>
                    <InputNumber min={0} />
                  </Form.Item>
                  <Form.Item
                    label={intl.formatMessage({ id: 'pages.laborRate' })}
                    name={['ResourceGroup', 'billLaborRate']}
                    rules={[{ required: true }]}
                  >
                    <InputNumber min={0.01} step={0.01} />
                  </Form.Item>
                  <Form.Item
                    label={intl.formatMessage({ id: 'pages.dailyProdCapacity' })}
                    name={['ResourceGroup', 'dailyProdQty']}
                    rules={[{ required: true }]}
                  >
                    <InputNumber min={0} />
                  </Form.Item>
                  <Form.Item label={intl.formatMessage({ id: 'pages.dailyProdRate' })} name={['ResourceGroup', 'dailyProdRate']}>
                    <InputNumber min={0.01} step={0.01} />
                  </Form.Item>
                </Col>
              </Row>
            </Card>
          </Form>
        </Col>
        <Col span={24}>
          <Resource ContextData={record} />
        </Col>
      </Row>
      <Modal
        title={intl.formatMessage({ id: 'pages.materialSelection' })}
        visible={visible}
        destroyOnClose={true}
        onCancel={switchModal}
        footer={false}
      ></Modal>
    </PageHeaderWrapper>
  );
};

export default ViewPage;
